package club.beimeng.emailserver.utils;



import club.beimeng.emailserver.utils.Property;
import lombok.Data;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;

@Data
@Component
public class AccountDistribution { // 获取配置类 首先得获取账号列表.
    int pointNumber = 0;// 轮询指针

    ArrayList<Item> accounts = new ArrayList<>(); // 限制每个元素长度是2，第一个是账号，第二个是授权码

    private final static java.util.logging.Logger logger = java.util.logging.Logger.getLogger("AccountDistribution");

    public String[] getSender(){ // 账号分享类。要保证每个账号的时间间隔至少3秒

        if (accounts.size() == 0){
            logger.info("初始化加载账户列表");
            if (Property.ACCOUNTS == null){
                logger.warning("properties未成功加载 - 加载失败");
                return null;
            }
            Property.ACCOUNTS.forEach( (account -> {
                accounts.add(new Item(account.getEmailNumber(), account.getEmailCode(), null));
                logger.info("账号池添加：" + account.getEmailNumber());
            }) );
        }

        Item item = accounts.get(pointNumber);
        if (item.lastUsingTime != null){
            int mills = (int) ((new Date().getTime() - item.lastUsingTime.getTime()) / 1000);
            if (mills < (Property.TIME_DELAY * 1000)){
                logger.warning("等待账号:" + item.emailNumber +"冷却" + ((3 * 1000) - mills )+ "毫秒");
                try {
                    Thread.sleep((3 * 1000) - mills);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                logger.warning("" + item.emailNumber +"冷却结束");
            }
            pointNumber += 1;
            pointNumber %= accounts.size();
            return  new String[]{item.emailNumber,item.emailCode};
        }
        item.lastUsingTime = new Date();
        pointNumber += 1;
        pointNumber %= accounts.size();
        logger.info("派发账号" + item.emailNumber + "序列号" + pointNumber);
        return new String[]{item.emailNumber,item.emailCode};
    }


    @Data
    public static class Item { // 内容承载体类

        public Item(String emailNumber, String emailCode, Date lastUsingTime) {
            this.emailNumber = emailNumber;
            this.emailCode = emailCode;
            this.lastUsingTime = lastUsingTime;
        }

        private String emailNumber;

        private String emailCode;

        Date lastUsingTime; // 上次使用时间

    }

}
